import Request from './request'
import apiList from './apis.js'
import store from '@/anaf/store/index.js'

const anafRequest = new Request();
export default function http(
	url,
	data = {},
	toastBefore = '', // 请求前加载提示
	toastAfter = true, // 请求后错误提示
) {
	let api = getApiPath(url);

	
	/* 请求之前拦截器 */
	anafRequest.interceptor.request((config, cancel) => {
		let token = uni.getStorageSync('token');
		if (api.auth && !token) {
			uni.hideLoading()
			uni.redirectTo({
				url: '/pages/login/login',
				// animationType: 'pop-in',
				animationDuration: 200
			});
		}
		
		token && anafRequest.setConfig(config => {
			config.header.Authorization = token
		})
		if (toastBefore !== '') {
			// uni.showLoading({
			// 	title: toastBefore,
			// 	mask: true
			// });
		}

		// uni.redirectTo({
		// 	url: '/pages/login/login',
		// 	animationDuration: 200
		// });
		return config
	});

	/* 请求之后拦截器 */
	anafRequest.interceptor.response( (response) => {
		// console.log(response)

		// if (toastBefore !== '') {
		// 	uni.hideLoading();
		// }
		
		
		if (response.status == 101) {
			uni.showToast({
				title: "登录已过期或注销,已阻止此次API请求" ,
				icon: 'none',
				duration: 1000,
				mask: true
			});
			
			// uni.redirectTo({
			// 	url: '/pages/login/login',
			// 	animationType: 'pop-in',
			// 	animationDuration: 200
			// });


			// uni.redirectTo({
			// 	url: '/pages/login/login',
			// 	animationDuration: 1000
			// });
			// console.log(response)
			// console.log()
			// console.log(uni.$u)

			// uni.redirectTo({url:'/'})

			// uni.$u.route('/pages/login/login')

			throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
		}

		// if (response.status == 201) {
		// 	uni.showToast({
		// 		title: response.msg ,
		// 		icon: 'none',
		// 		duration: 1000,
		// 		mask: true
		// 	});
		// }
		return response
	})

	return anafRequest.request({
		url: api.url,
		data,
		method: api.method
	})

}

// 组装接口路径
function getApiPath(url) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}
